<?php

/*

Desktopd Colors
Copyright (C) 2015  Desktopd Developer(s)

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

https://www.gnu.org/licenses/agpl.html

*/


namespace Desktopd\Colors;


/*
    1x1 PNG base class
*/

abstract class PNGPixel {
    const SIGNATURE = "\x89PNG\r\n\x1a\n";
    
    /* Rendering intents */
    // for images preferring good adaptation to the output device gamut at the expense of colorimetric accuracy, such as photographs.
    const INTENT_PERCEPTUAL = 0;
    
    const INTENT_RELATIVE_COLORIMETRIC = 1;
    // for images requiring colour appearance matching (relative to the output device white point), such as logos.
    
    const INTENT_SATURATION = 2;
    // for images preferring preservation of saturation at the expense of hue and lightness, such as charts and graphs.
    
    const INTENT_ABSOLUTE_COLORIMETRIC = 3;
    // for images requiring preservation of absolute colorimetry, such as previews of images destined for a different output device (proofs).
    
    
    protected $data = '';
    
    
    protected function buildChunk ($type, $data) {
        $type = "$type";
        if (4 !== strlen($type)) {
            throw new \ErrorException('Invalid type');
        }
        
        $data = "$data";
        $crc32 = hash('crc32b', $type . $data, true);
        $length = pack('N', strlen($data));
        return $length . $type . $data . $crc32;
    }
    
    protected function buildIDAT ($pixels) {
        return gzcompress("$pixels", 9);
    }
    
    protected function sRGB ($renderingIntent = self::INTENT_ABSOLUTE_COLORIMETRIC) {
        return pack('C', max(0, min(3, (int) $renderingIntent)));
    }
    
    protected function gAMA () {
        return pack('N', 45455); // gamma 1/2.2 (sRGB)
    }
    
    protected function cHRM () {
        // sRGB values
        return pack(
            'N*'
            , 31270 // White point x
            , 32900 // White point y
            , 64000 // Red x
            , 33000 // Red y
            , 30000 // Green x
            , 60000 // Green y
            , 15000 // Blue x
            , 6000 // Blue y
        );
    }
    
    public function __toString () {
        return $this->data;
    }
}


// vim: ts=4 et ai

